package com.ailesson.user.api;


import com.ailesson.common.core.AuthContextHolder;
import com.ailesson.common.except.ServiceException;
import com.ailesson.common.reply.R;
import com.ailesson.user.config.WechatProperties;
import com.ailesson.user.model.reply.UserInfoReply;
import com.ailesson.user.model.reply.WxJsapiSignatureReply;
import com.ailesson.user.service.UserInfoService;
import com.ailesson.common.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
@Tag(name = "公众号认证模块")
@Controller
@RequestMapping("/api/user/wechat")
public class WechatApiController {

    @Autowired
    private UserInfoService userInfoService;


    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WechatProperties wechatProperties;


    //授权跳转
    @Operation(summary = "授权跳转")
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl,
                            HttpServletRequest request) {
        String url = wxMpService.getOAuth2Service().buildAuthorizationUrl(wechatProperties.getUserInfoUrl(),
                WxConsts.OAuth2Scope.SNSAPI_USERINFO,
                URLEncoder.encode(returnUrl.replace("ail", "#")));

        return "redirect:"+url;
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) {
        try {
            //拿着code请求
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            //获取openid
            String openId = accessToken.getOpenId();

            //获取微信信息
            WxOAuth2UserInfo auth2UserInfo = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);

            //获取微信信息添加数据库
            UserInfoReply userInfo = userInfoService.getOrSaveUserInfoOpenId(auth2UserInfo,openId);

            //授权完成之后，跳转具体功能页面
            //生成token，按照一定规则生成字符串，可以包含用户信息
            String token = JwtUtil.createToken(userInfo.getId(),userInfo.getNickName());

            if(returnUrl.indexOf("?") == -1) {
                return "redirect:"+returnUrl+"?"+JwtUtil.TOKEN_NAME+"="+token;
            } else {
                return "redirect:"+returnUrl+"&"+JwtUtil.TOKEN_NAME+"="+token;
            }

        }catch (WxErrorException e) {
            throw new ServiceException(e.getError().getErrorCode(),e.getError().getErrorMsg());
        }
    }


    @Operation(summary = "分享签名")
    @GetMapping("/getSignature")
    @ResponseBody
    public R getSignature(@RequestParam("url") String url) throws WxErrorException {
        String currentUrl = url.replace("ail", "#");
        WxJsapiSignature jsapiSignature = wxMpService.createJsapiSignature(currentUrl);

        WxJsapiSignatureReply wxJsapiSignature = new WxJsapiSignatureReply();
        BeanUtils.copyProperties(jsapiSignature, wxJsapiSignature);
        wxJsapiSignature.setUserEedId(Base64Utils.encodeToString(AuthContextHolder.getUserId().toString().getBytes(StandardCharsets.UTF_8)));
        return R.success(wxJsapiSignature);
    }





}
